package cn.seczone.codecheck.utils;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class RecursiveTaskExample {
    private static final int MAX_THREADS = 10; // 最大线程数
    private static final AtomicInteger taskCount = new AtomicInteger(0); // 未完成的任务数量

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(MAX_THREADS);

        // 执行递归任务
        performRecursiveTask(executor, 0);

        // 等待所有任务完成
        waitForTasksToComplete(executor);

        // 关闭线程池
        executor.shutdown();
    }

    private static void performRecursiveTask(ExecutorService executor, int level) {
//        if (level < MAX_THREADS) {
            RecursiveTask task = new RecursiveTask(level);

            taskCount.incrementAndGet(); // 未完成任务数量加一
            executor.execute(() -> {
                task.compute();
                performRecursiveTask(executor, level + 1);
                taskCount.decrementAndGet(); // 任务完成后数量减一
            });
//        }
    }

    private static void waitForTasksToComplete(ExecutorService executor) {
        try {
            while (taskCount.get() > 0) {
                Thread.sleep(100);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    private static class RecursiveTask {
        private final int level;

        public RecursiveTask(int level) {
            this.level = level;
        }

        public void compute() {
            // 递归任务的逻辑
            System.out.println("Level " + level + ": Executing task in thread " + Thread.currentThread().getName());

            // 模拟耗时操作
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}